import { getCommTreeByXid, s_getcommontableinfo, s_getcommontableinfoBycondition, s_getTableInfo, s_operateInfo, s_updateInfo } from "@/services/basis";
import { ActionType, ProCard, ProColumns, ProColumnType, ProForm, ProFormInstance, ProFormText, ProTable } from "@ant-design/pro-components";
import { useModel, useRequest } from "@umijs/max";
import { Button, Col, message, Modal, Row, Space, Tag, Tree, TreeNodeProps } from "antd"
import { DataNode } from "antd/es/tree";
import { useRef, useState } from "react";

const App:React.FC=()=>{
   const [treeData,setTreeData]=useState();
   const [selectNode,setSelectNode]=useState<DataNode>();
   const [selectCategoryID,setSelectCategoryID]=useState<any[]>([]);
   const [selectedRecord,setSelectedRecord]=useState<DataType[]>([]);
   const [selectedRowId,setSelectedRowId]=useState([]);
   const [queryCondition,setQueryCondition]=useState({type:2});

   const [open,setOpen]=useState(false);
   const [etype,setEtype]=useState(1);

   const mtable_ref=useRef<ActionType>();
   const mform_ref=useRef<ProFormInstance>();
   const stable_ref=useRef<ActionType>();
   const [expandKeys,setExpandKeys]=useState([]);
   const { initialState, setInitialState } = useModel('@@initialState');
   const [selectedLineKeys,setSelectedLineKeys]=useState<any[]>([]);

   
   useRequest(()=>getCommTreeByXid({x_id:1,source_table:'base_custom_category'}),{  
      onSuccess:(data)=>{
         setTreeData(data.ctree);
         setExpandKeys(data.keys);
      },
    });
   
    //点击左侧树
    function selectTreeNode(node:DataNode){
      setSelectNode(node);
      // alert(JSON.stringify(node));
      arr=[];//先置为空，再取数据
      arr.push(node.key);
      getNodeKeys(node);
      setSelectCategoryID(arr.filter((item)=>item!=null));
      mtable_ref.current?.reloadAndRest?.();
    }

   //  新增
   function add(){
      if(selectCategoryID.length==0)
         message.warning('请先选择类别');
      else{
         setOpen(true);
         setEtype(1);
      }
   }
    
   async function saveInfo(){
       var fdata=({custom_category_id:selectNode?.key,vc_id:selectedRowId});
      //  alert(JSON.stringify(fdata));
       const x=await s_updateInfo({x_id:1,operater_id:initialState?.currentUser?.userid,source:'base_custom',etype:1,fdata});
       if(x.success){
          message.success('保存成功');
          setOpen(false);
          setEtype(1);
          mtable_ref.current?.reloadAndRest?.();
       }else
          message.error('保存失败，请联系管理员');
   }

   //  操作
   async function operateInfo(n:number){
      // source,x_id,operater_id,otype,id
      if(selectedRecord.length==0)
         message.warning('请选择要操作的行');
      else{
       const x=await s_operateInfo({x_id:1,source:'base_custom',
               operater_id:initialState?.currentUser?.userid,otype:n,id:selectedRecord[0].id});
       if(x.success){
         message.success('操作成功');
         mtable_ref.current?.reloadAndRest?.();
       }else
         message.error('操作错误，请联系管理员。');
      }
   }

   async function query(){
      const fdata={...mform_ref.current?.getFieldsValue(),type:2};//1供应商2店铺
      // alert(JSON.stringify(fdata));
      setQueryCondition(fdata);
      stable_ref.current?.reloadAndRest?.();
   }
    
  //--生成本级和下级的分类ID数组---先取本节点及下级节点值，再共同选
      var arr:any[]=[];
       //定义一个递归函数，获取选中节点下的所有key
      //  function getNodeKeys(node:{key:any,title:any,children:any[]}){
         function getNodeKeys(node:any){
            if(node.children.length>0)
                  node.children.map((item:any)=>{
                     arr.push(item.key);
                     if(item.children.length>0){
                          arr.push(getNodeKeys(item));
                     }
                 });
          }
      
          interface DataType{
            id:number,xcode:string,code:string,name:string,sname:string,creditcode:string,present:string,
            telephone:string,mobilephone:string,email:string,connector:string,
            salecategory2:string,purchasecategory2:string,xlevel:string,
            country:string,province:string,city:string,address:string,
            memo:string,state:number,status:number
          }

          const columns:ProColumns<DataType>[]=[
            {dataIndex:'id',hidden:true},
            // {dataIndex:'xcode',title:'内部码'},
            {dataIndex:'code',title:'编码'},{dataIndex:'name',title:'名称'},{dataIndex:'sname',title:'简称'},
            // {dataIndex:'creditcode',title:'统一社会信用代码'},{dataIndex:'present',title:'法人代表'},{dataIndex:'telephone',title:'固定电话'},
            // {dataIndex:'mobilephone',title:'手机'},{dataIndex:'email',title:'电子邮箱'},{dataIndex:'connector',title:'联系人'},
            // {dataIndex:'salecategory2',title:'采购品类'},{dataIndex:'purchasecategory2',title:'供货品类'},{dataIndex:'xlevel',title:'等级'},
            // {dataIndex:'country',title:'国家'},{dataIndex:'province',title:'省区'},{dataIndex:'city',title:'城市'},
            {dataIndex:'address',title:'详细地址'},{dataIndex:'memo',title:'备注'}, 
            // {dataIndex:'state',title:'标识',fixed:'right',width:80,hidden:true,
            //    render:(text)=>{
            //       switch(text){
            //          case 1: return <Tag color='red'>临时</Tag>;break;
            //          case 2: return <Tag>正式</Tag>;break;
            //          default: return <>{text}</>;
            //       }
            //    }
            // },
            {dataIndex:'status',title:'状态',fixed:'right',width:80,
               render:(text)=>{
                  switch(text){
                     case 1: return <Tag >正常</Tag>;break;
                     case 2: return <Tag color="blue" >关闭</Tag>;break;
                     case 3: return <Tag  color="red">删除</Tag>;break;
                  }
               }
            }, 
          ];

//===========================================================================================
  return (
        <Row gutter={8}>
         <Col span={6}  >
           <ProCard title='店铺分类' style={{height:'85vh'}}>
               {/* {JSON.stringify(selectCategoryID)} */}
               <Tree treeData={treeData}  blockNode onClick={(e,node)=>selectTreeNode(node)}
                  expandedKeys={expandKeys}
                  onExpand={(keys:any)=>setExpandKeys(keys)}
               />
           </ProCard>  
         </Col>
         <Col span={18}  >
           <ProCard title='店铺档案' style={{height:'85vh'}} 
            extra={<Space>
                    <Button onClick={()=>add()}>新增</Button>
                    <Button onClick={()=>operateInfo(2)}>关闭</Button>
                    <Button onClick={()=>operateInfo(3)}>删除</Button>
                    <Button onClick={()=>operateInfo(1)}>恢复</Button>
                    {/* <Button onClick={()=>alert('暂缓。录入等级、历史交易统计、自由项等')}>店铺信息</Button> */}

            </Space>}
           >
            {/* {JSON.stringify(selectedRecord)} */}
               <ProTable<DataType> 
                   actionRef={mtable_ref}
                   columns={columns}
                   rowKey='id'
                   rowSelection={{
                     type:'radio',
                     selectedRowKeys:selectedLineKeys,
                     // onSelect:(selectedRows:any,selectedRowKeys)=>setSelectedRecord(selectedRows),
                     onChange:(selectedRowKeys, selectedRows, info)=>{
                        setSelectedRecord(selectedRows);
                        setSelectedLineKeys(selectedRowKeys);
                     },
                   }}
                 onRow={(record)=>{
                    return {
                     onClick:()=>{
                        const k=record.id;
                // if(selectedKeys.includes(k) )
                //      setSelectedKeys(selectedKeys.filter(item=>item.id!=k));
                // else
                     setSelectedLineKeys([k]);
                     setSelectedRecord([record]);
              },
            }
           }}
                   pagination={{
                     defaultPageSize:10,
                     showQuickJumper:true,
                   }}
                   request={async ()=>{
                     // x_id,cate_id,id,source
                     const x=await s_getcommontableinfo({x_id:1,source:'v_custom',id:0,cate_id:selectCategoryID});
                     return{
                        data:x.data[0],
                        success:true,
                     }
                   }}
                   scroll={{y:'65vh'}}
                   search={false}
                />

           </ProCard>
         </Col>
         <Modal open={open} destroyOnClose={true} closable width='80%'  cancelButtonProps={{hidden:true}} okButtonProps={{hidden:true}}
             onCancel={()=>setOpen(false)} onClose={()=>setOpen(false)}  
         >
            <ProCard  title='新增店铺'
                extra={<Space>
                   <Button onClick={()=>saveInfo()}>保存</Button>
                   <Button onClick={()=>setOpen(false)}>取消</Button>
                </Space>}>
            <ProForm formRef={mform_ref} submitter={false}
            //   onFinish={()=>saveInfo()}
              initialValues={etype==1?{
                              status:1,          
                           }:{
                              ...selectedRecord[0],
                           }}
            >
               <Row gutter={8}>
                  <Col span={8}>
                     <ProFormText name='name' label='店铺名称' width={300}/>
                     <ProFormText name='mobilephone' label='手机' width={300} /> 
                </Col>
                <Col span={8}>
                    <ProFormText name='vccategory' label='采购类目' width={300} />
                     {/* <ProFormText name='salecategory' label='供货类目' width={300} /> */}
                </Col>
                <Col span={8}>
                    <ProFormText name='province' label='省区' width={300} />
                    <ProFormText name='city' label='城市'  width={300}/>
                    
                </Col>
                </Row>
                <Button onClick={()=>query()}>开始查询</Button> 
                {/* {JSON.stringify(selectedRowId)} */}
                <ProTable<DataType> 
                   actionRef={stable_ref}
                   columns={columns}
                   rowKey='id'
                   rowSelection={{
                     type:'checkbox',
                     // onSelect:(selectedRows:any,selectedRowKeys)=>setSelectedRecord(selectedRows),
                     onChange:(selectedRowKeys:any, selectedRows, info)=>setSelectedRowId(selectedRowKeys),
                   }}
                   pagination={{
                     pageSize:10,
                     showQuickJumper:true,
                   }}
                   request={async ()=>{
                     // x_id,cate_id,id,source
                     const x=await s_getcommontableinfoBycondition({x_id:1,source:'v_vcdocument',tdata:queryCondition});
                     return{
                        data:x.data[0],
                        success:true,
                     }
                   }}
                   scroll={{x:'200%'}}
                   search={false}
                />
            </ProForm>
            </ProCard>
        </Modal>
        </Row>
        
     );
}

export default App;